package com.caishi.lkx.user.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caishi.lkx.common.AdminBaseApi;
import com.caishi.lkx.common.config.DiamondConfig;
import com.caishi.lkx.common.context.RequireContext;
import com.caishi.lkx.common.ienum.PlatformType;
import com.caishi.lkx.common.role.Role;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.exam.service.IExamService;
import com.caishi.lkx.user.dto.GroupPermission;
import com.caishi.lkx.user.dto.GroupPermissionDto;
import com.caishi.lkx.user.model.*;
import com.caishi.lkx.user.service.*;
import com.caishi.lkx.user.service.impl.UserServiceImpl;
import com.zzw.common.exception.BizException;

import com.caishi.lkx.user.login.LoginServiceComposite;

import io.swagger.v3.oas.annotations.Operation;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;


@Tag(name = "机构相关接口")
@RestController
@RequestMapping("/user/sys/group")
@Slf4j
public class GroupApi extends AdminBaseApi<IGroupService, GroupModel, Long> {
    @Resource
    private IGroupService groupService;

    @Resource
    private IAdminUserService adminUserService;

    @Resource
    private ILoginInfoService loginInfoService;

    @Resource
    private UserServiceImpl userService;


    @Resource
    private IExamService examService;

   // @Value("${wechat.xcx.qrcode-url}")
   // private String wechatXcxQRCodeUrl;

    @Resource
    private LoginServiceComposite loginServiceComposite;

    @Resource
    private DiamondConfig diamondConfig;
    @Resource
    private IChannelBusinessService channelBusinessService;

    @Override
    public IGroupService loadService() {
        return groupService;
    }

    @Override
    @PostMapping("update")
    public GroupModel add(@RequestBody GroupModel entity)  {
        return groupService.update(entity);
    }
    @Override
    protected List<GroupModel> listCover(List<GroupModel> result, JSONObject otherParam){
        List<String> managerIdList = new ArrayList<>();
        result.forEach(r->{
            managerIdList.add(r.getManagerId());
        });
        if (!managerIdList.isEmpty()){
            List<UserModel> userList = channelBusinessService.getUserList(managerIdList);
            userList.forEach(u->{
                for (GroupModel groupModel : result) {
                    if (groupModel.getManagerId().equals(u.getId())){
                        ChannelBusinessModel channelBusiness = new ChannelBusinessModel();
                        channelBusiness.setMobile(u.getMobile());
                        groupModel.setChannelBusiness(channelBusiness);
                    }
                }
            });
        }
        return  result;
    };
    @Operation(summary = "设置权限")
    @PostMapping("/set-permission")
    public GroupModel setPermission(@RequestBody GroupPermissionDto groupPermissionDto) throws BizException {

        GroupModel groupModel = groupService.getById(groupPermissionDto.getGroupId());
        if (groupModel == null) {
            throw new BizException("平台不存在");
        }
        List<GroupPermission> permissionMap =  new ArrayList<GroupPermission>();
        permissionMap.add(GroupPermission.builder().type(GroupPermission.Type.zhiye).enable(true).examActionIds(groupPermissionDto.getExamList()).industryActionIds(groupPermissionDto.getIndustryList()).build());
        groupModel.setPermissionMap(permissionMap);
        return loadService().update(groupModel);
    }


    @Override
    protected LambdaQueryWrapper<GroupModel> baseWrapper(GroupModel model, JSONObject otherParam) {
        PlatformType scope = null;
        String platformType = otherParam.getStr("platformType");
        //0是无效 1是有效
        String status = otherParam.getStr("status");
        LocalDateTime time1 = otherParam.getLocalDateTime("time1", null);
        LocalDateTime time2 = otherParam.getLocalDateTime("time2", null);
        if (StrUtil.isNotBlank(platformType)) {
            scope = PlatformType.valueOf(platformType);
        }
        PlatformType platform = userContext.currentPlatform();
        String registerDay = otherParam.getStr("registerDay", "");
        return super.baseWrapper(model.clearEmptyStringField("name", "startTime", "endTime", "expireTime"), otherParam)
                .like(StrUtil.isNotBlank(model.getName()), GroupModel::getName, model.getName())
                .orderByDesc(GroupModel::getCreatedTime);
    }


    @GetMapping("/getPermissionByGroupId/{groupId}")
    @Roles({Role.admin})
    public List<GroupPermission> getPermissionByGroupId(@PathVariable Long groupId) {
        return groupService.getById(groupId).getPermissionMap();
    }

    @GetMapping("/current-ip")
    @Roles
    public String currentGroupIp() {
        return userContext.currentIp();
    }


    @GetMapping("/detail/{id}")
    @Operation(summary = "机构详情")
    @Roles(Role.none)
    @Override
    public GroupModel detail(@PathVariable Long id) {
        return GroupModel.builder().permissionMap(super.detail(id).getPermissionMap()).build();
    }

    @GetMapping("/config")
    @Operation(summary = "平台配置")
    @Roles(Role.none)
    @RequireContext({com.caishi.lkx.common.context.Role.APP,com.caishi.lkx.common.context.Role.PC})
    public Map<String, Object> config() {
        log.info("获取机构配置,机构id:{}",context.getGroupId());
       var group =  groupService.getById(context.getGroupId());
        return group.getConfig();
    }
    @GetMapping("/watermark")
    @Operation(summary = "平台水印")
    @Roles(Role.none)
    @RequireContext({com.caishi.lkx.common.context.Role.APP,com.caishi.lkx.common.context.Role.PC})
    public String watermark() {
        log.info("获取机构配置,机构id:{}",context.getGroupId());
        var group =  groupService.getById(context.getGroupId());
        return group.getWatermark();
    }
}
